package com.sqlist.shareserver.resolver.impl;

import com.google.gson.reflect.TypeToken;
import com.sqlist.shareserver.connection.ConnectionPool;
import com.sqlist.shareserver.dto.LocationDTO;
import com.sqlist.shareserver.dto.MessageDTO;
import com.sqlist.shareserver.resolver.DataResolver;
import com.sqlist.shareserver.util.Const;
import com.sqlist.shareserver.util.GsonUtils;
import com.sqlist.shareserver.util.LocationMap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by SqList on 2018/6/13.
 */

@Slf4j
@Component
public class LocationDTODataResolver implements DataResolver {
    @Autowired
    private LocationMap locationMap;
    @Autowired
    private ConnectionPool connectionPool;

    @Override
    public void resolve(String messageString, Channel channel) {
        log.info("resolve()");
        Type type = new TypeToken<MessageDTO<LocationDTO>>(){}.getType();
        MessageDTO<LocationDTO> locationDTOMessageDTO = GsonUtils.getInstance().fromJson(messageString, type);

        if (locationDTOMessageDTO.getData() != null) {
            log.info("{} 的定位信息， 位置为({}, {})",
                    locationDTOMessageDTO.getUsername(), locationDTOMessageDTO.getData().getLatitude(), locationDTOMessageDTO.getData().getLongitude());
            locationMap.addLocationDTO(locationDTOMessageDTO.getUsername(), locationDTOMessageDTO.getData());
        }

        MessageDTO<Map<String, LocationDTO>> mapMessageDTO = new MessageDTO<>();
        mapMessageDTO.setCode(Const.REQUEST_SUCCESS);
        mapMessageDTO.setMsg("所有在线人的定位信息");
        mapMessageDTO.setType("locationDTO");
        mapMessageDTO.setData(locationMap.getLocationMap());

        Map<String, Channel> concurrentHashMap = connectionPool.getUserMap();
        byte[] req = (GsonUtils.getInstance().toJson(mapMessageDTO) + "|").getBytes();
        log.info("给所有人发送定位信息");
        for (Channel c : concurrentHashMap.values()) {
            ByteBuf byteBuf = Unpooled.buffer(req.length);
            byteBuf.writeBytes(req);
            c.writeAndFlush(byteBuf);
        }
    }
}
